{% extends "pc/template.html" %}

{% block title %}
失物招领列表
{% endblock %}

{% include 'pc/公共样式配置/CSS总样式.html' %}

{% block css %}
<link rel="stylesheet" href="/static/HubUI/css/sweetalert2.css">
<style>
     /* SweetAlert2 层级样式 */
     .swal2-container {
        z-index: 99999 !important;
    }
    .swal2-popup {
        z-index: 99999 !important;
    }
    .swal2-backdrop-show {
        z-index: 99998 !important;
    }
    .container-xxl { padding: 2rem 1.5rem; }
    .card { margin: 1rem 0; border: none; border-radius: 1rem; box-shadow: 0 0.125rem 0.25rem rgba(0,0,0,0.075); transition: all 0.3s ease; }
    .card-header { background: #fff; border-bottom: 1px solid rgba(0,0,0,0.05); padding: 1.5rem; border-radius: 1rem 1rem 0 0 !important; }
    .card-header h5 { color: #566a7f; font-weight: 600; margin: 0; }
    .btn-primary { background: #696cff; border-color: #696cff; padding: 0.5rem 1rem; font-weight: 500; transition: all 0.2s ease; }
    .btn-primary:hover { background: #5f61e6; border-color: #5f61e6; transform: translateY(-1px); }
    .table-responsive { margin: 0; padding: 1rem; }
    .table thead th { background: #f8f9fa; color: #566a7f; font-weight: 600; border-bottom: 2px solid #e9ecef; padding: 1rem; }
    .table tbody td { padding: 1rem; vertical-align: middle; color: #697a8d; border-bottom: 1px solid #e9ecef; }
    .table tbody tr { transition: all 0.2s ease; }
    .table tbody tr:hover { background: #f8f9fa; }
    .action-buttons .btn { padding: 0.4rem 0.6rem; margin: 0 0.2rem; border-radius: 0.5rem; transition: all 0.2s ease; }
    .action-buttons .btn:hover { transform: translateY(-2px); }
    .dropdown-menu { border: none; border-radius: 0.5rem; box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15); padding: 0.5rem; min-width: 160px; }
    .dropdown-item { padding: 0.6rem 1rem; color: #697a8d; border-radius: 0.4rem; display: flex; align-items: center; gap: 0.5rem; transition: all 0.2s ease; }
    .dropdown-item:hover { background: #f8f9fa; color: #566a7f; }
    .dropdown-item.view { color: #03c3ec; }
    .dropdown-item.edit { color: #ffab00; }
    .dropdown-item.delete { color: #ff3e1d; }
    .dropdown-item.view:hover { background: rgba(3,195,236,0.1); }
    .dropdown-item.edit:hover { background: rgba(255,171,0,0.1); }
    .dropdown-item.delete:hover { background: rgba(255,62,29,0.1); }
    .dropdown-toggle::after { display: none; }
    .action-btn { background: #f8f9fa; border: 1px solid #d9dee3; color: #697a8d; padding: 0.4rem 0.8rem; border-radius: 0.5rem; display: flex; align-items: center; gap: 0.5rem; transition: all 0.2s ease; }
    .action-btn:hover { background: #f5f5f9; border-color: #d9dee3; color: #566a7f; }
    .action-btn i { font-size: 1.1rem; }
    .pagination { margin: 1rem 0 0 0; justify-content: center; }
    .pagination .page-link { padding: 0.5rem 0.75rem; color: #566a7f; background-color: #fff; border: 1px solid #d9dee3; margin: 0 0.2rem; border-radius: 0.5rem; transition: all 0.2s ease; }
    .pagination .page-item.active .page-link { background-color: #696cff; border-color: #696cff; color: #fff; }
    .pagination .page-link:hover { color: #696cff; background-color: #f5f5f9; border-color: #d9dee3; transform: translateY(-1px); }
    .pagination .page-item.disabled .page-link { color: #a3a4cc; pointer-events: none; background-color: #fff; border-color: #d9dee3; }
    .modal-content { border: none; border-radius: 1rem; box-shadow: 0 0.5rem 1rem rgba(0,0,0,0.15); }
    .modal-header { border-bottom: 1px solid rgba(0,0,0,0.05); padding: 1.5rem; }
    .modal-title { color: #566a7f; font-weight: 600; }
    .modal-body { padding: 1.5rem; }
    .modal-footer { border-top: 1px solid rgba(0,0,0,0.05); padding: 1.5rem; }
    .form-label { color: #566a7f; font-weight: 500; margin-bottom: 0.5rem; }
    .form-control { border-radius: 0.5rem; border: 1px solid #d9dee3; padding: 0.5rem 1rem; transition: all 0.2s ease; }
    .form-control:focus { border-color: #696cff; box-shadow: 0 0 0 0.2rem rgba(105,108,255,0.25); }
    .form-check { margin-bottom: 0.5rem; }
    .form-check-input { border-radius: 0.25rem; }
    .form-check-input:checked { background-color: #696cff; border-color: #696cff; }
    .form-check-label { color: #697a8d; }
    .avatar-skeleton { width: 40px; height: 40px; border-radius: 50%; background: linear-gradient(90deg,#f0f0f0 25%,#e0e0e0 50%,#f0f0f0 75%); background-size: 200% 100%; animation: skeleton-loading 1.5s infinite; }
    @keyframes skeleton-loading { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
    @media (max-width: 768px) { .container-xxl { padding: 1rem; } .card-header { padding: 1rem; } .table-responsive { padding: 0.5rem; } .action-buttons .btn { padding: 0.3rem 0.5rem; margin: 0 0.1rem; } }
</style>
{% endblock %}

{% block content %}
<div class="container-xxl flex-grow-1 container-p-y">
    <div class="card">
        <div class="card-header d-flex justify-content-between align-items-center">
            <h5 class="mb-0">失物招领列表</h5>
            <div class="d-flex align-items-center gap-2">
                <input type="text" class="form-control" id="searchInput" placeholder="搜索物品名称/认领者/位置..." style="width: 220px;">
                <button type="button" class="btn btn-primary" onclick="showAddModal()">
                    <i class="bx bx-plus"></i> 新增失物招领
                </button>
            </div>
        </div>
        <div class="card-body">
            <div class="table-responsive">
                <table class="table table-hover">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>物品名称</th>
                            <th>状态</th>
                            <th>认领者</th>
                            <th>联系方式</th>
                            <th>位置</th>
                            <th>创建时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody id="lostTableBody">
                        <!-- 数据通过JS动态加载 -->
                    </tbody>
                </table>
            </div>
            <nav aria-label="Page navigation">
                <ul class="pagination" id="pagination">
                    <!-- 分页按钮通过JS动态加载 -->
                </ul>
            </nav>
        </div>
    </div>

    <!-- 新增/编辑/查看模态框 -->
    <div class="modal fade" id="lostModal" tabindex="-1" aria-hidden="true">
        <div class="modal-dialog modal-dialog-centered modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title" id="lostModalTitle">新增失物招领</h5>
                    <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button>
                </div>
                <div class="modal-body">
                    <form id="lostForm">
                        <input type="hidden" id="lost_and_found_id" name="lost_and_found_id">
                        <div class="row">
                            <div class="mb-3 col-md-6">
                                <label class="form-label">物品名称</label>
                                <input type="text" class="form-control" id="lost_and_found_name" name="lost_and_found_name" required>
                            </div>
                            <div class="mb-3 col-md-6">
                                <label class="form-label">物品状态</label>
                                <select class="form-control" id="lost_and_found_status" name="lost_and_found_status" required onchange="onStatusChange()">
                                    <option value="1">待认领</option>
                                    <option value="2">已认领</option>
                                    <option value="3">已失效</option>
                                </select>
                            </div>
                        </div>
                        <div class="row">
                            <div class="mb-3 col-md-6">
                                <label class="form-label">认领者姓名</label>
                                <input type="text" class="form-control" id="lost_and_found_claimer_name" name="lost_and_found_claimer_name">
                            </div>
                            <div class="mb-3 col-md-6">
                                <label class="form-label">认领者联系方式</label>
                                <input type="text" class="form-control" id="lost_and_found_claimer_contact" name="lost_and_found_claimer_contact">
                            </div>
                        </div>
                        <div class="row">
                            <div class="mb-3 col-md-6">
                                <label class="form-label">物品位置</label>
                                <input type="text" class="form-control" id="lost_and_found_location" name="lost_and_found_location">
                            </div>
                            <div class="mb-3 col-md-6">
                                <label class="form-label">物品描述</label>
                                <input type="text" class="form-control" id="lost_and_found_description" name="lost_and_found_description">
                            </div>
                        </div>
                        <div class="mb-3">
                            <label class="form-label">图片上传</label>
                            <input type="file" class="form-control" id="lost_images" name="lost_images" accept="image/*" multiple>
                            <div class="mt-2" id="imagePreview"></div>
                        </div>
                    </form>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-outline-secondary" data-bs-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="lostModalSaveBtn" onclick="submitLostForm()">保存</button>
                </div>
            </div>
        </div>
    </div>

    <!-- 查看模态框（只读）可复用上面模态框，JS控制表单禁用 -->
</div>
{% endblock %}

{% block js %}
<script src="/static/HubUI/js/sweetalert2.js"></script>
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<script>
let allLosts = [];
let currentPage = 1;
const itemsPerPage = 10;
let currentMode = 'add'; // add/edit/view
let currentEditId = '';

// 页面加载
window.addEventListener('DOMContentLoaded', function() {
    getLostList();
    document.getElementById('searchInput').addEventListener('input', onSearchInput);
});

function getLostList(keyword = '') {
    Swal.fire({ title: '加载中...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    let url = '/api/lostAndFound/get_lost_and_found_list/';
    if (keyword) url = `/api/lostAndFound/search_lost_and_found/?keyword=${encodeURIComponent(keyword)}`;
    axios.get(url)
        .then(res => {
            if (res.data.code === 200) {
                allLosts = res.data.data;
                currentPage = 1;
                renderLostTable();
                renderPagination();
            } else {
                Swal.fire('错误', res.data.msg, 'error');
            }
        })
        .catch(() => Swal.fire('错误', '获取列表失败', 'error'))
        .finally(() => Swal.close());
}

function renderLostTable() {
    const tbody = document.getElementById('lostTableBody');
    tbody.innerHTML = '';
    const start = (currentPage - 1) * itemsPerPage;
    const end = start + itemsPerPage;
    const pageData = allLosts.slice(start, end);
    pageData.forEach(item => {
        const tr = document.createElement('tr');
        tr.innerHTML = `
            <td>${item.lost_and_found_id}</td>
            <td>${item.lost_and_found_name}</td>
            <td>${statusText(item.lost_and_found_status)}</td>
            <td>${item.lost_and_found_claimer_name || '-'}</td>
            <td>${item.lost_and_found_claimer_contact || '-'}</td>
            <td>${item.lost_and_found_location || '-'}</td>
            <td>${item.create_time}</td>
            <td class="action-buttons">
                <div class="dropdown">
                    <button class="action-btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
                        <i class="bx bx-dots-vertical-rounded"></i><span>操作</span>
                    </button>
                    <ul class="dropdown-menu">
                        <li><a class="dropdown-item view" href="#" onclick="viewLost('${item.lost_and_found_id}')"><i class="bx bx-show"></i><span>查看</span></a></li>
                        <li><a class="dropdown-item edit" href="#" onclick="editLost('${item.lost_and_found_id}')"><i class="bx bx-edit"></i><span>编辑</span></a></li>
                        <li><a class="dropdown-item delete" href="#" onclick="deleteLost('${item.lost_and_found_id}')"><i class="bx bx-trash"></i><span>删除</span></a></li>
                    </ul>
                </div>
            </td>
        `;
        tbody.appendChild(tr);
    });
}

function renderPagination() {
    const pagination = document.getElementById('pagination');
    const totalPages = Math.ceil(allLosts.length / itemsPerPage);
    let html = '';
    html += `<li class="page-item ${currentPage === 1 ? 'disabled' : ''}"><a class="page-link" href="#" onclick="changePage(${currentPage - 1})"><i class="bx bx-chevron-left"></i></a></li>`;
    for (let i = 1; i <= totalPages; i++) {
        html += `<li class="page-item ${currentPage === i ? 'active' : ''}"><a class="page-link" href="#" onclick="changePage(${i})">${i}</a></li>`;
    }
    html += `<li class="page-item ${currentPage === totalPages ? 'disabled' : ''}"><a class="page-link" href="#" onclick="changePage(${currentPage + 1})"><i class="bx bx-chevron-right"></i></a></li>`;
    pagination.innerHTML = html;
}

function changePage(page) {
    if (page < 1 || page > Math.ceil(allLosts.length / itemsPerPage)) return;
    currentPage = page;
    renderLostTable();
    renderPagination();
}

function onSearchInput(e) {
    const keyword = e.target.value.trim();
    getLostList(keyword);
}

function statusText(status) {
    if (status == 1) return '待认领';
    if (status == 2) return '已认领';
    if (status == 3) return '已失效';
    return '-';
}

function showAddModal() {
    currentMode = 'add';
    currentEditId = '';
    document.getElementById('lostModalTitle').textContent = '新增失物招领';
    document.getElementById('lostForm').reset();
    document.getElementById('lost_and_found_id').value = '';
    document.getElementById('imagePreview').innerHTML = '';
    enableLostForm(true);
    document.getElementById('lostModalSaveBtn').style.display = '';
    new bootstrap.Modal(document.getElementById('lostModal')).show();
}

function viewLost(id) {
    currentMode = 'view';
    currentEditId = id;
    axios.get(`/api/lostAndFound/get_lost_and_found/${id}/`).then(res => {
        if (res.data.code === 200) {
            fillLostForm(res.data.data);
            document.getElementById('lostModalTitle').textContent = '查看失物招领';
            enableLostForm(false);
            document.getElementById('lostModalSaveBtn').style.display = 'none';
            new bootstrap.Modal(document.getElementById('lostModal')).show();
        } else {
            Swal.fire('错误', res.data.msg, 'error');
        }
    });
}

function editLost(id) {
    currentMode = 'edit';
    currentEditId = id;
    axios.get(`/api/lostAndFound/get_lost_and_found/${id}/`).then(res => {
        if (res.data.code === 200) {
            fillLostForm(res.data.data);
            document.getElementById('lostModalTitle').textContent = '编辑失物招领';
            enableLostForm(true);
            document.getElementById('lostModalSaveBtn').style.display = '';
            new bootstrap.Modal(document.getElementById('lostModal')).show();
        } else {
            Swal.fire('错误', res.data.msg, 'error');
        }
    });
}

function fillLostForm(data) {
    document.getElementById('lost_and_found_id').value = data.lost_and_found_id || '';
    document.getElementById('lost_and_found_name').value = data.lost_and_found_name || '';
    document.getElementById('lost_and_found_status').value = data.lost_and_found_status || 1;
    document.getElementById('lost_and_found_claimer_name').value = data.lost_and_found_claimer_name || '';
    document.getElementById('lost_and_found_claimer_contact').value = data.lost_and_found_claimer_contact || '';
    document.getElementById('lost_and_found_location').value = data.lost_and_found_location || '';
    document.getElementById('lost_and_found_description').value = data.lost_and_found_description || '';
    // 图片预览
    let html = '';
    if (data.images && data.images.length > 0) {
        data.images.forEach(img => {
            html += `<img src="${img.image}" style="max-width:80px;max-height:80px;margin-right:8px;border-radius:6px;">`;
        });
    }
    document.getElementById('imagePreview').innerHTML = html;
}

function enableLostForm(enable) {
    [
        'lost_and_found_name',
        'lost_and_found_status',
        'lost_and_found_claimer_name',
        'lost_and_found_claimer_contact',
        'lost_and_found_location',
        'lost_and_found_description',
        'lost_images'
    ].forEach(id => {
        const el = document.getElementById(id);
        if (el) el.disabled = !enable;
    });
}

function submitLostForm() {
    const form = document.getElementById('lostForm');
    const formData = new FormData(form);
    // 状态为已认领时，校验认领者信息
    if (formData.get('lost_and_found_status') == '2') {
        if (!formData.get('lost_and_found_claimer_name')) {
            Swal.fire('提示', '认领者姓名为必填项', 'warning'); return;
        }
        if (!formData.get('lost_and_found_claimer_contact')) {
            Swal.fire('提示', '认领者联系方式为必填项', 'warning'); return;
        }
    }
    // 新增或编辑
    let url = '/api/lostAndFound/create_lost_and_found/';
    if (currentMode === 'edit') {
        url = `/api/lostAndFound/update_lost_and_found/${currentEditId}/`;
    }
    Swal.fire({ title: '提交中...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
    axios.post(url, formData)
        .then(res => {
            if (res.data.code === 200) {
                // 图片上传
                const files = document.getElementById('lost_images').files;
                if (files.length > 0) {
                    uploadLostImages((currentMode === 'edit' ? currentEditId : res.data.data.lost_and_found_id), files, () => {
                        Swal.fire({ icon: 'success', title: '成功', text: '操作成功', showConfirmButton: false, timer: 1200 });
                        getLostList();
                        bootstrap.Modal.getInstance(document.getElementById('lostModal')).hide();
                    });
                } else {
                    Swal.fire({ icon: 'success', title: '成功', text: '操作成功', showConfirmButton: false, timer: 1200 });
                    getLostList();
                    bootstrap.Modal.getInstance(document.getElementById('lostModal')).hide();
                }
            } else {
                Swal.fire('错误', res.data.msg, 'error');
            }
        })
        .catch(() => Swal.fire('错误', '提交失败', 'error'))
        .finally(() => Swal.close());
}

function uploadLostImages(lostId, files, cb) {
    let uploaded = 0;
    for (let i = 0; i < files.length; i++) {
        const fd = new FormData();
        fd.append('image', files[i]);
        axios.post(`/api/lostAndFound/upload_lost_and_found_image/${lostId}/`, fd)
            .then(() => {
                uploaded++;
                if (uploaded === files.length) {
                    Swal.fire({ icon: 'success', title: '成功', text: '图片上传成功', showConfirmButton: false, timer: 1200 });
                    cb();
                }
            })
            .catch(() => {
                uploaded++;
                if (uploaded === files.length) {
                    Swal.fire({ icon: 'success', title: '成功', text: '图片上传成功', showConfirmButton: false, timer: 1200 });
                    cb();
                }
            });
    }
}

function deleteLost(id) {
    Swal.fire({ title: '确认删除', text: '确定要删除该记录吗？', icon: 'warning', showCancelButton: true, confirmButtonText: '确定', cancelButtonText: '取消' })
        .then(result => {
            if (result.isConfirmed) {
                Swal.fire({ title: '删除中...', allowOutsideClick: false, didOpen: () => Swal.showLoading() });
                axios.delete(`/api/lostAndFound/delete_lost_and_found/${id}/`)
                    .then(res => {
                        if (res.data.code === 200) {
                            Swal.fire({ icon: 'success', title: '成功', text: '删除成功', showConfirmButton: false, timer: 1200 });
                            getLostList();
                        } else {
                            Swal.fire('错误', res.data.msg, 'error');
                        }
                    })
                    .catch(() => Swal.fire('错误', '删除失败', 'error'))
                    .finally(() => Swal.close());
            }
        });
}

function onStatusChange() {
    const status = document.getElementById('lost_and_found_status').value;
    document.getElementById('lost_and_found_claimer_name').required = status == '2';
    document.getElementById('lost_and_found_claimer_contact').required = status == '2';
}
</script>
{% endblock %}

{% block nav_left %}
{% include "pc/components/左侧导航栏.html" %}
{% endblock %}

{% block NavBar %}
{% endblock %}

{% include 'pc/公共样式配置/JS总样式.html' %}

{% block footer %}
    {% include "pc/components/Footer.html" %}
{% endblock %}